# 存储计划单
import json
import sys
sys.path.append("..")
from flask import request
from create_id import get_id
from db_client import *
from send_email_func import send_email
from config import *

def store_plan():
    # 存储计划单, 并发送通知邮件, 将相关的需求单状态改为 已规划
    token = request.headers.get('token')
    flag, right = token_client.check_token(token)
    if not flag:
        t = {
            'state': 'false',
            'msg': '无权限, 存储计划单失败'
        }
        return json.dumps(t, ensure_ascii=False)
    else:
        data = json.loads(request.get_data())
        item_id = data['purchase_item_id']
        item_name = data['purchase_item_name']
        item_count = data['purchase_item_count']
        total_money = data['purchase_item_total_money']
        # fixme
        demand_ids = data['demand_ids']
        date = data['create_purchase_date']
        unit_price = data['unit_price']
        supplier_id = data['supplier_id']
        _id = get_id('JH')
        approval_date = ''
        approval_staff_id = ''

        # 将列表转化为字符串
        str_demand_ids = ','.join(demand_ids)

        flag2 = mysql_client.store_plan(_id, item_name, item_id, item_count, total_money, str_demand_ids,
                                        date, approval_date, approval_staff_id, unit_price, supplier_id)
        if flag2:
            t = {
                'state': 'true',
                'msg': 'success'
            }
            # 发送通知邮件
            if email and password:
                send_msg = '计划单编号:' + _id + '总金额:' + total_money
                send_email(email, password, send_msg, smtp_server, port, to_email=to_email)

            # 更新相关需求单状态
            for demand_id in demand_ids:
                data = {
                    'de_if': '已规划'
                }
                mysql_client.update_demand(data, demand_id)
                
            return json.dumps(t, ensure_ascii=False)
        else:
            t = {
                'state': 'false',
                'msg': '存储计划单失败'
            }
            return json.dumps(t, ensure_ascii=False)
